package com.sudo.boot.netty.ws;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class NettyWebServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(new ChannelInitializer<>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        // 对http协议的支持，使用http的编码器和解码器
                        pipeline.addLast(new HttpServerCodec());
                        // 聚合解码 httpRequest/httpContent/lastHttpContent 到 fullHttpRequest
                        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                        // 心跳检测
                        pipeline.addLast(new IdleStateHandler(6, 0, 0, TimeUnit.SECONDS));
                        // 超时处理器
                        pipeline.addLast(new HeartBeatHandler());
                        // 将http协议升级为ws协议，支持websocket
                        pipeline.addLast(new WebSocketServerProtocolHandler("/ws",null,true,64*1024,true,true,10000L));
                        // 消息处理
                        pipeline.addLast(new WebSocketHandler());
                    }
                });
        try {
            ChannelFuture channelFuture = bootstrap.bind(8000).sync();
            System.out.println("启动成功");
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
